package com.zdpx.pxframework.seata.init;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * SEATA初始化设置
 *
 * @Description
 * @Author Cheng XiaoXiao
 * @Date 2021/02/26 11:01
 * @Version 1.0
 */
public class ApplicationSeataInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
        String applicationName = environment.getProperty("spring.application.name");
        setSystemProperty(environment, "seata.service.vgroup-mapping." + applicationName + "-group", "default");
    }

    /**
     * 设置环境变量，并设置默认值
     *
     * @param environment 环境
     * @param key         键
     * @param defaultVal  默认值
     */
    private void setSystemProperty(ConfigurableEnvironment environment, String key, String defaultVal) {
        String property = environment.getProperty(key);
        System.setProperty(key, property == null ? defaultVal : property);
    }
}
